package liujinliang.natappvip.cc.uibestpractice;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import liujinliang.natappvip.cc.uibestpractice.adapter.MsgAdapter;
import liujinliang.natappvip.cc.uibestpractice.entity.Msg;

public class MainActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<>();

    private Button sendBtn;

    private EditText inputText;

    private RecyclerView recyclerView;

    private MsgAdapter msgAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 msgList
        initMsgList();

        // 初始化 sendBtn, inputText, recyclerView
        inputText = (EditText) findViewById(R.id.input_text);
        sendBtn = (Button) findViewById(R.id.send_btn);
        recyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);

        // 初始化 LayoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // 初始化 Adapter
        msgAdapter = new MsgAdapter(msgList);
        recyclerView.setAdapter(msgAdapter);

        // 为发送消息的按钮添加事件
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 接受用户输入
                String content = inputText.getText().toString();

                if ( ! "".equals(content)) {
                    // 初始化发送信息
                    Msg msg = new Msg(content, Msg.TYPE_SEND);
                    msgList.add(msg);

                    // 当有新的消息时，刷新 recyclerView 中的显示
                    msgAdapter.notifyItemInserted(msgList.size() - 1);

                    // 将 recyclerView 定位到最后一行
                    recyclerView.scrollToPosition(msgList.size() - 1);

                    // 清空输入框中的内容
                    inputText.setText("");
                }
            }
        });
    }

    public void initMsgList() {
        Msg msg1 = new Msg("Hello Gene！", Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("Hello Hardy！", Msg.TYPE_SEND);
        msgList.add(msg2);
        Msg msg3 = new Msg("Time to have a dinner.", Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}
